package pri.zxx.testdemo;

/**
 * @author xigua
 * @desc
 * @createTime 2022-03-15-下午8:09
 */
public class FooBar {
    private int n;
    final Object o = new Object();

    public FooBar(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) {
        synchronized (o) {
            try {
                for (int i = 0; i < n; i++) {
                    printFoo.run();
                    o.notify();
                    o.wait();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            o.notify();
        }

    }

    public void bar(Runnable printBar) {
        synchronized (o) {
            try {
                for (int i = 0; i < n; i++) {
                    printBar.run();
                    o.notify();
                    o.wait();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            o.notify();
        }
    }

    public static void main(String[] args) {

        FooBar fooBar = new FooBar(1);

        new Thread(() -> fooBar.foo(() -> System.out.print("foo"))).start();

        new Thread(() -> fooBar.bar(() -> System.out.print("bar"))).start();

//        TimeUtils.pause(1, 0, 0);
    }
}

